//package com.dcits.filter.cros;
//
//import lombok.extern.slf4j.Slf4j;
//import org.springframework.stereotype.Component;
//import org.springframework.util.StringUtils;
//
//import javax.servlet.*;
//import javax.servlet.http.Cookie;
//import javax.servlet.http.HttpServletRequest;
//import javax.servlet.http.HttpServletResponse;
//import java.io.IOException;
//import java.util.*;
//
///**
// * 综合Web安全过滤器（CORS + CSRF + Cookie安全）
// */
//@Slf4j
//@Component
//public class CommonWebFilter implements Filter {
////    @Autowired
////    private SecurityProperties securityProperties;
//
//    // ================== 可配置参数 ==================
//    // CSRF配置
//    private final static String csrfCookieName = "XSRF-TOKEN";
//    private final static String csrfHeaderName = "X-XSRF-TOKEN";
//
//    // Cookie安全配置
//    private final static String cookieDomain = "";
//    private final static boolean cookieSecure = true;
//    private final static String cookieSameSite = "Strict";
//
//    @Override
//    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
//
//        HttpServletRequest request = (HttpServletRequest) servletRequest;
//        HttpServletResponse response = (HttpServletResponse) servletResponse;
//        // ================== 1. CORS处理 ==================
//        handleCors(request, response);
//
//        // ================== 2. CSRF防护 ==================
//        if (!handleCsrf(request, response)) {
//            return; // CSRF验证失败直接阻断
//        }
//
//        // ================== 3. Cookie安全加固 ==================
////        secureCookies(response);
//
//        // ================== 4. 其他安全响应头 ==================
//        addSecurityHeaders(response);
//
//        // ================== 5. 继续过滤器链 ==================
//        if (!"OPTIONS".equalsIgnoreCase(request.getMethod())) {
//            filterChain.doFilter(request, response);
//        }
//    }
//
//    // ================== CORS核心逻辑 ==================
//    private void handleCors(HttpServletRequest request, HttpServletResponse response) {
//        String origin = request.getHeader("Origin");
//
//        if (StringUtils.hasText(origin)) {
//            // 设置CORS响应头
//            response.setHeader("Access-Control-Allow-Origin", "*");
////            response.setHeader("Access-Control-Allow-Methods", String.join(",", securityProperties.getCors().getAllowedMethods()));
////            response.setHeader("Access-Control-Allow-Headers", String.join(",", securityProperties.getCors().getAllowedHeaders()));
////            response.setHeader("Access-Control-Max-Age", String.valueOf(securityProperties.getCors().getMaxAge().getSeconds()));
//
////            if (securityProperties.getCors().isAllowCredentials()) {
////                response.setHeader("Access-Control-Allow-Credentials", "true");
////            }
//
//            // 特殊处理预检请求
//            if (isPreFlightRequest(request)) {
//                response.setStatus(HttpServletResponse.SC_OK);
//                log.debug("Handled CORS pre-flight request for {}", origin);
//            }
//        }
//    }
//
//    // ================== CSRF核心逻辑 ==================
//    private boolean handleCsrf(HttpServletRequest request, HttpServletResponse response) {
//        // 排除GET/HEAD/OPTIONS等安全方法
//        if (isSafeMethod(request.getMethod())) {
//            return true;
//        }
//
////        if (securityProperties.getCsrf().isEnabled()) {
//            // 从Cookie和Header获取令牌
//            String csrfToken = getCookieValue(request, csrfCookieName);
//            String headerToken = request.getHeader(csrfHeaderName);
//
//            // 验证令牌有效性
//            if (StringUtils.isEmpty(csrfToken) || !csrfToken.equals(headerToken)) {
//                response.setStatus(HttpServletResponse.SC_FORBIDDEN);
//                log.warn("CSRF validation failed. Cookie: {}, Header: {}", csrfToken, headerToken);
//                return false;
//            }
//
//            // 每次请求刷新CSRF令牌（可选）
//            setCsrfCookie(response, generateNewToken());
////        }
//        return true;
//    }
//
//    // ================== Cookie安全加固 ==================
//    private void secureCookies(HttpServletResponse response) {
//        // 确保所有Set-Cookie头都包含安全属性
//        Collection<String> headers = response.getHeaders("Set-Cookie");
//        if (headers == null || headers.isEmpty()) return;
//
//        List<String> newHeaders = new ArrayList<>();
//        for (String header : headers) {
//            String secureHeader = header
//                    + "; Domain=" + cookieDomain
//                    + "; Secure"
//                    + "; HttpOnly"
//                    + "; SameSite=" + cookieSameSite;
//            newHeaders.add(secureHeader);
//        }
//
//        response.setHeader("Set-Cookie", String.join(",", newHeaders));
//    }
//
//    // ================== 安全响应头 ==================
//    private void addSecurityHeaders(HttpServletResponse response) {
//        // 基础安全头
//        response.setHeader("X-Content-Type-Options", "nosniff");
//        response.setHeader("X-Frame-Options", "DENY");
//        response.setHeader("X-XSS-Protection", "1; mode=block");
//        response.setHeader("Referrer-Policy", "strict-origin-when-cross-origin");
//
//        // 现代浏览器安全头
//        response.setHeader("Content-Security-Policy",
//                "default-src 'self'; script-src 'self' 'unsafe-inline' cdn.example.com");
//    }
//
//    // ================== 工具方法 ==================
//    private boolean isPreFlightRequest(HttpServletRequest request) {
//        return "OPTIONS".equalsIgnoreCase(request.getMethod())
//                && request.getHeader("Access-Control-Request-Method") != null;
//    }
//
//    private boolean isSafeMethod(String method) {
//        return Arrays.asList("GET", "HEAD", "OPTIONS", "TRACE").contains(method);
//    }
//
//    private String getCookieValue(HttpServletRequest request, String name) {
//        Cookie[] cookies = request.getCookies();
//        if (cookies != null) {
//            for (Cookie cookie : cookies) {
//                if (cookie.getName().equals(name)) {
//                    return cookie.getValue();
//                }
//            }
//        }
//        return null;
//    }
//
//    private void setCsrfCookie(HttpServletResponse response, String token) {
//        String cookie = String.format(
//                "%s=%s; Path=/; Domain=%s; Max-Age=%d; %s; SameSite=%s",
//                csrfCookieName,
//                token,
//                cookieDomain,
//                86400,
//                cookieSecure ? "Secure" : "",
//                cookieSameSite
//        );
//        response.addHeader("Set-Cookie", cookie);
//    }
//
//    private String generateNewToken() {
//        return UUID.randomUUID().toString();
//    }
//
//
//}